package com.example.lenovo.asia5b.my.myWallet.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.Spinner;

import com.bigkoo.pickerview.TimePickerView;
import com.example.lenovo.asia5b.commodity.activity.ServiceActivity;
import com.example.lenovo.asia5b.my.bean.BankBean;
import com.example.lenovo.asia5b.ui.DownloadPicture;
import com.example.lenovo.asia5b.ui.LoadingDalog;
import com.example.lenovo.asia5b.util.DateUtils;
import com.example.lenovo.asia5b.util.DensityUtil;
import com.example.lenovo.asia5b.util.ICallBack;
import com.example.lenovo.asia5b.util.JsonTools;
import com.example.lenovo.asia5b.util.JsonTools2;
import com.example.lenovo.asia5b.util.Logic;
import com.example.lenovo.asia5b.util.MD5;
import com.example.lenovo.asia5b.util.Setting;
import com.wushi.lenovo.asia5b.R;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import app.BaseActivity;
import fay.frame.ui.U;

import static com.example.lenovo.asia5b.util.SharedPreferencesUtils.getUserBean;
import static com.wushi.lenovo.asia5b.R.id.edit_money;
import static com.wushi.lenovo.asia5b.R.id.public_btn_left;
import static com.wushi.lenovo.asia5b.R.id.txt_transfer_time;

/**
 * Created by lenovo on 2017/6/30.
 */

public class EBankingRechargeActivity extends BaseActivity implements ICallBack {
    private List<BankBean> listBanks,listOutBanks ;
    private List<String> listBankNameOnes;
    private Spinner spr_bank,spr_bank_two;
    private Spinner spr_out_bank,spr_out_bank_two;
    private String bank_id = "",bank_out_id = "";
    private LoadingDalog loadingDalog;
    //充值类型
    private String type = "3";
    private String images = "";
    private CheckBox chb_protocol;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_e_banking_recharge);
        initView();
        bankData();
    }

    public void initView() {
        loadingDalog = new LoadingDalog(EBankingRechargeActivity.this);
        spr_bank = (Spinner)findViewById(R.id.spr_bank);
        spr_bank_two  = (Spinner)findViewById(R.id.spr_bank_two);
        spr_out_bank = (Spinner)findViewById(R.id.spr_out_bank);
        spr_out_bank_two  = (Spinner)findViewById(R.id.spr_out_bank_two);

        F.id(R.id.ll_xy).clicked(this);
        chb_protocol = (CheckBox)findViewById(R.id.chb_protocol);
        F.id(R.id.public_title_name).text(getResources().getString(R.string.top_up_recharge));
        F.id(public_btn_left).clicked(this);
        F.id(txt_transfer_time).clicked(this);
        F.id(R.id.btn_recharge).clicked(this);
        F.id(R.id.txt_images).clicked(this);
        if (getIntent().hasExtra("type")) {
            type = getIntent().getStringExtra("type");
        }
        F.id(R.id.txt_money).text("RM "+getUserBean().user_money);
        F.id(edit_money).getEditText().addTextChangedListener(new EditChangedListener(F.id(edit_money).getEditText()));
        chb_protocol.setChecked(true);
    }

    /**
     * 充值
     */
    public void rechargeData() {
        loadingDalog.show();
        //充值金额
        String money = F.id(edit_money).getText().toString();
        //手机号
        String phone = F.id(R.id.txt_phone).getText().toString();
        //转入银行
        String bank = bank_id;
        //转出银行
        String fromBank =bank_out_id;
        //流水号
        String serial = F.id(R.id.edit_serial).getText().toString();
        //转账时间
        String payTime = DateUtils.dataOne(F.id(txt_transfer_time).getText().toString()+"-00");
        //凭证
        String images = this.images;
        if (money.indexOf(".")!=-1) {
            float aa = Float.parseFloat(money);
            aa = DensityUtil.getScale(aa);
            money = aa+"";
        }
        try {
            Map<String, String> parmaMap = new HashMap<String, String>();
            String url = Setting.RECHARGE;
            String user_id = getUserBean().user_id;
            Date date = new Date();
            String time = String.valueOf(date.getTime());
            String[] sort = {"user_id"+user_id,"money"+money,"type"+type,"bank"+bank,"phone"+phone,"fromBank"+fromBank,"serial"+serial,"paytime"+payTime,"time"+time};
            String sortStr = Logic.sortToString(sort);
            String md5_32 = MD5.MD5EncryptionFor32(MD5.MD5EncryptionFor32(sortStr));//二次加密
            parmaMap.put("user_id", user_id);
            parmaMap.put("phone",phone);
            parmaMap.put("money",money);
            parmaMap.put("type",type);
            parmaMap.put("bank",bank);
            parmaMap.put("fromBank",fromBank);
            parmaMap.put("serial",serial);
            parmaMap.put("paytime",payTime);
            parmaMap.put("time",time);
            parmaMap.put("sign",md5_32);
            Map<String, String> formMap2 = new HashMap<String, String>();
            formMap2.put("images",images);
            JsonTools2.dataHttps(this, url, parmaMap,formMap2, 0);
        }catch (Exception e) {

        }

    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case public_btn_left:
                finish();
                break;
            case txt_transfer_time:
                TimePickerView pvTime = new TimePickerView.Builder(EBankingRechargeActivity.this, new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date2, View v) {//选中事件回调
                        String time = getTime(date2);
                        F.id(txt_transfer_time).text(time);
                    }
                })
                        .setType(TimePickerView.Type.YEAR_MONTH_DAY_HOUR_MIN)//默认全部显示
                        .setCancelText(getResources().getString(R.string.qx))//取消按钮文字
                        .setSubmitText(getResources().getString(R.string.confirm))//确认按钮文字
                        .setContentSize(13)//滚轮文字大小
                        .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                        .isCyclic(true)//是否循环滚动
                        .setSubmitColor(ContextCompat.getColor(EBankingRechargeActivity.this,R.color.wathet))//确定按钮文字颜色
                        .setCancelColor(ContextCompat.getColor(EBankingRechargeActivity.this,R.color.wathet))//取消按钮文字颜色
                        .setLabel(getResources().getString(R.string.n),getResources().getString(R.string.y),getResources().getString(R.string.r),
                                getResources().getString(R.string.s),getResources().getString(R.string.f),"秒")
                        .isCenterLabel(false)
                        .build();
                pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
                pvTime.show();
                break;
            case R.id.btn_recharge:
                if (TextUtils.isEmpty(F.id(edit_money).getText().toString())) {
                    U.Toast(EBankingRechargeActivity.this,getResources().getString(R.string.czjebnwk));
                } else if (TextUtils.isEmpty(F.id(R.id.txt_phone).getText().toString())) {
                    U.Toast(EBankingRechargeActivity.this,getResources().getString(R.string.my_data_hint_4));
                }   else if (TextUtils.isEmpty(F.id(R.id.edit_serial).getText().toString())) {
                    U.Toast(EBankingRechargeActivity.this,getResources().getString(R.string.lshbnwk));
                }else if (TextUtils.isEmpty(F.id(txt_transfer_time).getText().toString())) {
                    U.Toast(EBankingRechargeActivity.this,getResources().getString(R.string.zzsjbnwk));
                }else if (TextUtils.isEmpty(images)) {
                    U.Toast(EBankingRechargeActivity.this,getResources().getString(R.string.pzbnwk));
                }else if (!chb_protocol.isChecked()) {
                    U.Toast(EBankingRechargeActivity.this, getResources().getString(R.string.qgxyhxy));
                }
                else{
                    if (!TextUtils.isEmpty(F.id(edit_money).getEditText().getText().toString())) {
                        if (F.id(edit_money).getEditText().getText().toString().substring(0,1).equals(".")) {
                            return;
                        }
                    }
                    rechargeData();
                }
                break;
            case R.id.txt_images:
                loadingDalog.showPhoto();
                break;
            case R.id.ll_xy:
                intent = new Intent(EBankingRechargeActivity.this, ServiceActivity.class);
                intent.putExtra("xy","3");
                startActivity(intent);
                break;
            default:
                break;
        }
    }
    private Handler handler2 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            JSONObject result= null;
            try {
                result = new JSONObject(msg.obj.toString());
            } catch (Exception e) {
            }
            int action = msg.what;
            if (action == 0) {
                if (null != result && result instanceof JSONObject) {
                    try {
                        JSONObject json = (JSONObject) result;
                        int state = (int) json.getInt("State");
                        if (state == 0) {
                            U.Toast(EBankingRechargeActivity.this, getResources().getString(R.string.cg));
                            Intent intent = new Intent();
                            intent.putExtra("222",2222);
                            EBankingRechargeActivity.this.setResult(0, intent);
                            finish();
                        } else if (state == 1) {
                            U.Toast(EBankingRechargeActivity.this, getResources().getString(R.string.qmsb));
                        } else if (state == 2) {
                            U.Toast(EBankingRechargeActivity.this, getResources().getString(R.string.cscw));
                        } else if (state == 3) {
                            U.Toast(EBankingRechargeActivity.this, getResources().getString(R.string.zryhbnwk));
                        } else if (state == 4) {
                            U.Toast(EBankingRechargeActivity.this, getResources().getString(R.string.czjebnwk));
                        } else if (state == 5) {
                            U.Toast(EBankingRechargeActivity.this, getResources().getString(R.string.zcyhbnwk));
                        } else if (state == 6) {
                            U.Toast(EBankingRechargeActivity.this, getResources().getString(R.string.lshbnwk));
                        } else if (state == 7) {
                            U.Toast(EBankingRechargeActivity.this, getResources().getString(R.string.wdl));
                        }
                    } catch (Exception e) {
                    }
                }else {
//                U.Toast(EBankingRechargeActivity.this, "空值");
                }
                loadingDalog.dismiss();
            }  else if (action == 1) {
                if (null != result && result instanceof JSONObject) {
                    try {
                        JSONObject json = (JSONObject) result;
                        int state = (int) json.getInt("State");
                        if (state == 0) {
                            JSONArray bank = json.getJSONArray("bank");
                            listBanks = Logic.getListToBean(bank,new BankBean());
                            showBank();
                        } else if (state == 1) {
                            U.Toast(EBankingRechargeActivity.this, getResources().getString(R.string.qmsb));
                        } else if (state == 2) {
                            U.Toast(EBankingRechargeActivity.this, getResources().getString(R.string.cscw));
                        }
                    } catch (Exception e) {
                    }
                }
                rollOutBankData();
            }else if (action == 2) {
                if (null != result && result instanceof JSONObject) {
                    try {
                        JSONObject json = (JSONObject) result;
                        int state = (int) json.getInt("State");
                        if (state == 0) {
                            JSONArray bank = json.getJSONArray("bank");
                            listOutBanks = Logic.getListToBean(bank,new BankBean());
                            showOutBank();
                        } else if (state == 1) {
                            U.Toast(EBankingRechargeActivity.this, getResources().getString(R.string.qmsb));
                        } else if (state == 2) {
                            U.Toast(EBankingRechargeActivity.this, getResources().getString(R.string.cscw));
                        }
                    } catch (Exception e) {
                    }
                }
            }
        }
    };

    @Override
    public void logicFinish(Object result, int action) {
        Message msg = new Message();
        msg.what = action;
        msg.obj = result.toString();
        handler2.sendMessage(msg);
    }


    /**
     * 转入银行列表
     */
    public void bankData() {
        Map<String, String> parmaMap = new HashMap<String, String>();
        parmaMap.put("type","1");
        parmaMap.put("entry","0");
        String url = Setting.BANK;
        JsonTools.getJsonAll(this, url, parmaMap, 1);
    }


    /**
     * 转出银行列表
     */
    public void rollOutBankData() {
        Map<String, String> parmaMap = new HashMap<String, String>();
        parmaMap.put("type","1");
        parmaMap.put("entry","1");
        String url = Setting.BANK;
        JsonTools.getJsonAll(this, url, parmaMap, 2);
    }



    //银行选择器
    public void showBank() {
        getPriovince();
        ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(EBankingRechargeActivity.this,
                R.layout.simple_list_item,
                listBankNameOnes);
        spr_bank.setAdapter(adapter1);
        spr_bank.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){
            public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                final BankBean bean = listBanks.get(arg2);
                List<String> citys = getBanks(bean);
                ArrayAdapter<String> adapter2=new ArrayAdapter<String>(EBankingRechargeActivity.this,
                        R.layout.simple_list_item,
                        citys);
                spr_bank_two.setAdapter(adapter2);
                spr_bank_two.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){
                    public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                        bank_id = bean.chile.get(arg2).bank_id;
                    }
                    public void onNothingSelected(AdapterView<?> arg0) {
                    }
                });

            }
            public void onNothingSelected(AdapterView<?> arg0) {
                arg0.setVisibility(View.VISIBLE);
            }
        });
    }

    //转出银行选择器
    public void showOutBank() {
        getOutPriovince();
        ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(EBankingRechargeActivity.this,
                R.layout.simple_list_item,
                listBankNameOnes);
        spr_out_bank.setAdapter(adapter1);
        spr_out_bank.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){
            public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                final BankBean bean = listOutBanks.get(arg2);
                List<String> citys = getBanks(bean);
                ArrayAdapter<String> adapter2=new ArrayAdapter<String>(EBankingRechargeActivity.this,
                        R.layout.simple_list_item,
                        citys);
                spr_out_bank_two.setAdapter(adapter2);
                spr_out_bank_two.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){
                    public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                        bank_out_id = bean.chile.get(arg2).bank_id;
                    }
                    public void onNothingSelected(AdapterView<?> arg0) {
                    }
                });

            }
            public void onNothingSelected(AdapterView<?> arg0) {
                arg0.setVisibility(View.VISIBLE);
            }
        });
    }

    //  通过遍历集合获得银行的名字 --备用赋值给Spinner1
    private void getPriovince(){
        listBankNameOnes=new ArrayList<String>();
        for (BankBean bean : listBanks) {
            String cityname = bean.bank_name;
            listBankNameOnes.add(cityname);
        }
    }

    //  通过遍历集合获得银行的名字 --备用赋值给Spinner1
    private void getOutPriovince(){
        listBankNameOnes=new ArrayList<String>();
        for (BankBean bean : listOutBanks) {
            String cityname = bean.bank_name;
            listBankNameOnes.add(cityname);
        }
    }

    //  通过市获得区--备用赋值给Spinner2
    private List<String> getBanks(BankBean bean){
        List<String> listBankNameTwos=new ArrayList<String>();
        List<BankBean> citys = bean.chile;
        for (BankBean citys2 : citys) {
            String cityName = citys2.bank_name;
            listBankNameTwos.add(cityName);
        }
        return listBankNameTwos;
    }
    @Override
    protected void onActivityResult(int requestCode, int arg1, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, arg1, data);
        switch (requestCode) {
            case 101:// 相机
                if (data != null) {
                    if (data.getExtras() != null) {
                        Bundle bundle = data.getExtras();
                        Bitmap bitmap = bundle.getParcelable("data");
                        picture(bitmap);
                    } else {
                        U.Toast(this,getResources().getString(R.string.system_no_getpic));
                    }
                } else {
                    if (loadingDalog.getPhotoUrihotoUri() != null) {
                        try {
                            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), loadingDalog.getPhotoUrihotoUri());
                            if (null != bitmap) {
                                picture(DownloadPicture.smallOneFifth(bitmap));
                            } else {
                                U.Toast(this,getResources().getString(R.string.system_no_getpic));
                            }
                        }catch (Exception e) {
                        }
                    } else {
                        U.Toast(this,getResources().getString(R.string.system_no_getpic));
                    }
                }
                break;
            case 102:// 相册返回
                Uri uri = null;
                if (data != null) {
                    if (data.getData() != null) {
                        uri = data.getData();
                         try {
                             Bitmap bitmap  = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
                             picture(DownloadPicture.smallOneFifth(bitmap));
                         } catch (IOException e) {
                         e.printStackTrace();
                         }
                    }
                }
                break;
        }
    }

    public void picture(Bitmap photo) {
            BufferedOutputStream bos = null;
            if (photo != null) {
                File dirFile = new File(Setting.IMAGE_ROOTPATH);
                if (!dirFile.exists())
                    dirFile.mkdirs();
                SimpleDateFormat sDateFormat = new SimpleDateFormat(
                        "yyyyMMddhhmmss", Locale.ENGLISH);
                File uploadFile = new File(dirFile + "/"
                        + sDateFormat.format(new java.util.Date())
                        + ".jpg");

                char[] chars = "0123456789abcdef".toCharArray();
                StringBuilder sb = new StringBuilder("");
                int bit;
                try {
                    uploadFile.createNewFile();
                    bos = new BufferedOutputStream(new FileOutputStream(uploadFile));
                    photo.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                    FileInputStream fis = new FileInputStream(uploadFile);
                    byte[] b = new byte[fis.available()];
                    fis.read(b);
                    for (int i = 0; i < b.length; i++) {
                        bit = (b[i] & 0x0f0) >> 4;
                        sb.append(chars[bit]);
                        bit = b[i] & 0x0f;
                        sb.append(chars[bit]);
                    }

                    fis.close();
                    String photoFile = uploadFile.getAbsolutePath();
                    images = sb.toString();
                    F.id(R.id.txt_select).text(getResources().getString(R.string.yxztp));
                    F.id(R.id.txt_select).textColor(ContextCompat.getColor(EBankingRechargeActivity.this,R.color.my_333));
                } catch (IOException e) {
                    U.Toast(EBankingRechargeActivity.this, e.getLocalizedMessage());
                } finally {
                    if (bos != null) {
                        try {
                            bos.flush();
                            bos.close();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
        }
    }

    public String getTime(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyy-MM-dd-HH-mm");
        return format.format(date);
    }
}
